<?php

$app->group('/jokes', function () use ($app, $c, $redis) {
	$app->get('/', function () use ($app, $c) {
		
		$page = $app->request->get('page',1);
    	$size = 20;

		$nodes=array();
		$userids=array();

		$jokeTable = $c['Jokes\Table\Joke'];
		$userTable = $c['Common\Table\User'];
		$jokeUserTable = $c['Jokes\Table\User'];
		$jokeImageTable = $c['Jokes\Table\JokeImage'];

		foreach ($jokeTable->select(function (Zend\Db\Sql\Select $select) use($page,$size){
			$select->columns(array('id','content','createdAt'=>'created_at','user_id'))
				->order('id desc')->offset(($page-1)*$size)->limit($size);
		}) as $item) {
			$nodes[$item->id]=$item;
			$item->createdAt=date('Y-m-d',strtotime($item->createdAt));
			$userids[]=$item->user_id;
		}
		if(count($nodes)>0){
			$users=array();
			$users[0]=(object)array('id'=>0,'user_name'=>'unknown','avatar'=>'');
			foreach($userTable->select(function(Zend\Db\Sql\Select $select) use($userids){
				$select->columns(array('id','user_name','avatar'))->where(array('id'=>$userids));
			}) as $user){
				$users[$user->id]=$user;
			}
			
			foreach($nodes as $node){
				if(isset($users[$node->user_id])){
					$node->author=$users[$node->user_id];
				}else{
					$node->author=$users[0];
				}
			}
			$images=array();
			foreach($jokeImageTable->select(function(Zend\Db\Sql\Select $select) use($nodes){
				$select->where(array('joke_id' => array_keys($nodes)));
			}) as $image){
				$images[$image->joke_id]=$image->url;
			}

			foreach ($nodes as $key => $value) {
				if(isset($images[$value->id])){
					$value->image=$images[$value->id];
				}
			}
		}
		$nodes=array_values($nodes);
		if($app->request->isAjax()){
			$app->contentType('application/json; charset=utf8');
			echo json_encode($nodes);
		}else{
			$app->render('jokes/index.html');
		}
    })->name('jokes-home');
    $app->get('/:id', function($id) use($app,$c, $redis){

    });
});